package com.cloud.common.security.mdc;

import com.cloud.common.core.constant.CommonConstants;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Component
public class TraceFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            String traceId=request.getHeader(CommonConstants.traceId);
            MDC.put(CommonConstants.traceId,traceId);
            filterChain.doFilter(request,response);
        }finally {
            MDC.remove(CommonConstants.traceId);
        }
    }
}
